package controller;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

@SuppressWarnings("serial")
public class LinkServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		String domain = req.getParameter("domain");
		String reciprocal = req.getParameter("reciprocal");
		
		if(domain!=null && reciprocal!=null)
		{
			if(Utils.checkDomain(domain)&&Utils.checkDomain(reciprocal))
			{
				if(!Pattern.matches("^http://[\\w\\W]+", reciprocal))
				{
					reciprocal = "http://"+reciprocal;
				}
				String str = Utils.GetHtml(reciprocal, "utf-8");
				Document doc = Jsoup.parse(str);
				
				String strs = "<table width='100%'>";
				strs += "<tr><td><strong>Link</strong></td><td><strong>Anchor text</strong></td></tr>";
				
				Elements elements = doc.select("a");
				for (int i = 0; i < elements.size(); i++) {
					String a = elements.get(i).attr("href");
					
					if(Utils.fomatDomain(a).equals(Utils.fomatDomain(domain)))
					{
						strs+="<tr><td>"+a+"</td><td>"+elements.get(i).text()+"</td></tr>";
					}
				}
				strs += "</table>";
				
				req.setAttribute("strs", strs);
			}
		}
		req.setAttribute("domain", domain);
		req.setAttribute("reciprocal", reciprocal);
		try {
			req.getRequestDispatcher("link.jsp").forward(req, resp);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
